<template>
    <div class="download-container">
        <div class="header">
            <h1>云盘文件下载</h1>
            <p class="subtitle">安全快捷地获取您的文件</p>
        </div>

        <div v-if="!fileInfo" class="access-code-form">
            <h2>请输入4位访问码</h2>
            <div class="code-input-wrapper">
                <div class="code-inputs">
                    <template v-for="(digit, index) in 4" :key="index">
                        <input ref="codeInputs" type="text" maxlength="1" pattern="[0-9a-zA-Z]*" inputmode="numeric"
                            class="code-digit" v-model="codeDigits[index]" @input="handleDigitInput(index)"
                            @keydown="handleKeyDown($event, index)" @paste="handlePaste"
                            @focus="$event.target.select()" />
                    </template>
                </div>
                <el-button type="primary" class="verify-btn" @click="verifyAccessCode" :disabled="!isCodeComplete">
                    验证访问码
                </el-button>
            </div>
            <div v-if="errorMessage" class="error-message">
                <el-icon>
                    <WarningFilled />
                </el-icon>
                <span>{{ errorMessage }}</span>
            </div>
        </div>

        <div v-else class="file-info-card">
            <div class="file-icon">
                <el-icon :size="48">
                    <Document />
                </el-icon>
            </div>
            <h2>文件信息</h2>
            <div class="info-grid">
                <div class="info-item">
                    <div class="info-label">文件名</div>
                    <div class="info-value">{{ fileInfo.fileName }}</div>
                </div>
                <div class="info-item">
                    <div class="info-label">上传时间</div>
                    <div class="info-value">{{ formatDate(fileInfo.uploadTime) }}</div>
                </div>
            </div>
            <div class="actions">
                <el-button type="primary" size="large" class="download-btn" @click="downloadFile">
                    <el-icon>
                        <Download />
                    </el-icon> 下载文件
                </el-button>
                <el-button size="large" class="back-btn" @click="reset">
                    <el-icon>
                        <Back />
                    </el-icon> 返回
                </el-button>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useRoute } from 'vue-router'
import { WarningFilled, Document, Download, Back } from '@element-plus/icons-vue'
import http from '@/utils/request'
import list from '@/utils/url.js'


const route = useRoute()
const codeDigits = ref(['', '', '', ''])
const codeInputs = ref([])
const fileInfo = ref(null)
const errorMessage = ref('')

// 计算访问码是否已完整填写
const isCodeComplete = computed(() => {
    return codeDigits.value.every(digit => digit !== '' && /^[0-9a-zA-Z]$/.test(digit))
})

// 获取当前完整访问码
const getFullCode = () => {
    return codeDigits.value.join('')
}

// 如果URL中有code参数，自动填入
onMounted(() => {
    if (route.query.code) {
        const code = route.query.code.toString()
        if (code.length === 4) {
            for (let i = 0; i < 4; i++) {
                codeDigits.value[i] = code[i]
            }
        }
    }
    // 自动聚焦第一个输入框
    if (codeInputs.value[0]) {
        codeInputs.value[0].focus()
    }
})

// 处理数字输入
const handleDigitInput = (index) => {
    // 确保只能输入数字
    codeDigits.value[index] = codeDigits.value[index].replace(/[^0-9a-zA-Z]/g, '')

    // 如果有输入且不是最后一位，自动跳转到下一个输入框
    if (codeDigits.value[index] && index < 3) {
        codeInputs.value[index + 1].focus()
    }

    // 移除自动验证功能，只在点击按钮时验证
}

// 处理键盘事件
const handleKeyDown = (event, index) => {
    // 处理退格键
    if (event.key === 'Backspace') {
        if (codeDigits.value[index] === '' && index > 0) {
            // 如果当前框为空，焦点移到前一个输入框
            codeInputs.value[index - 1].focus()
        }
    }
    // 处理左右箭头
    else if (event.key === 'ArrowLeft' && index > 0) {
        codeInputs.value[index - 1].focus()
    }
    else if (event.key === 'ArrowRight' && index < 3) {
        codeInputs.value[index + 1].focus()
    }
    // 移除回车自动提交
    else if (event.key === 'Enter') {
        // 如果代码完整，则验证
        if (isCodeComplete.value) {
            verifyAccessCode()
        }
    }
}

// 处理粘贴事件
const handlePaste = (event) => {
    event.preventDefault()
    const pastedData = (event.clipboardData || window.clipboardData).getData('text')
    // 允许字母和数字，不再只限制数字
    const validChars = pastedData.replace(/[^0-9a-zA-Z]/g, '')

    // 限制只取前4位有效字符
    const validData = validChars.slice(0, 4)

    for (let i = 0; i < validData.length && i < 4; i++) {
        codeDigits.value[i] = validData[i]
    }

    // 移除自动验证，粘贴后不再自动提交
    // 焦点跳到下一个未填写的输入框
    const nextEmptyIndex = codeDigits.value.findIndex(digit => digit === '')
    if (nextEmptyIndex !== -1) {
        codeInputs.value[nextEmptyIndex].focus()
    } else if (codeDigits.value[3]) {
        // 如果最后一位也已填写，保持焦点在最后一位
        codeInputs.value[3].focus()
    }
}

// 验证访问码
const verifyAccessCode = () => {
    const fullCode = getFullCode()

    if (fullCode.length !== 4) {
        errorMessage.value = '请输入完整的4位访问码'
        return
    }

    // 先验证访问码是否有效
    http.get(list.list_file_api.validAccessCode, { code: fullCode }).then((res) => {
        if (res.code === 200) {
            // 构建下载URL
            const baseUrl = import.meta.env.VITE_APP_API_URL + import.meta.env.VITE_APP_BASE_API || window.location.origin
            const downloadUrl = `${baseUrl}/v1/file/download?code=${fullCode}`

            const token = localStorage.getItem('token')
            const clientIP = localStorage.getItem('ClientIP')

            // 下载文件
            http.downloadFile(downloadUrl, {}, { token, clientIP }).then(response => {
                // 检查响应类型是否为JSON (表示出现异常)
                const contentType = response.headers['content-type'] || '';
                if (contentType.includes('application/json')) {
                    // 处理JSON响应（异常情况）
                    if (response.data instanceof Blob) {
                        // 如果是Blob类型，需要先转换为文本
                        return response.data.text().then(text => {
                            try {
                                const result = JSON.parse(text);
                                // console.log('解析的JSON结果:', result);
                                // 显示错误信息
                                ElMessage.error(result.msg || '下载失败');
                            } catch (parseError) {
                            }
                        });
                    } else if (typeof response.data === 'object') {
                        // 如果已经是对象（可能某些HTTP客户端会自动解析JSON）
                        // console.log('JSON对象响应:', response.data);
                        ElMessage.error(response.data.msg || '下载失败');
                        // throw new Error(response.data.msg || '下载失败');
                    }
                }

                // 正常下载处理流程
                const blob = response.data;
                const disposition = response.headers['content-disposition'] || '';
                let fileName = 'downloaded_file';
                const match = disposition.match(/filename="?([^"]+)"?/);
                if (match) {
                    fileName = decodeURIComponent(match[1]);
                }

                // 触发下载
                const link = document.createElement('a');
                link.href = URL.createObjectURL(blob);
                link.download = fileName;
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                URL.revokeObjectURL(link.href);

                // 显示下载成功提示
                ElMessage.success('文件下载成功');
            })
        } else {
            ElMessage.error('验证失败，请检查访问码是否正确')
        }
    }).catch(err => {
        console.log(err);
        errorMessage.value = '访问码无效，请确认后重新输入'
    }).finally(() => {
        codeDigits.value = ['', '', '', '']
        if (codeInputs.value && codeInputs.value.length > 0) {
            codeInputs.value[0].focus()
        }
    })

}

// 格式化日期
const formatDate = (dateString) => {
    const date = new Date(dateString)
    const options = {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
    }
    return date.toLocaleDateString(undefined, options)
}



// 重置状态
const reset = () => {
    fileInfo.value = null
    codeDigits.value = ['', '', '', '']
    errorMessage.value = ''
    // 重置后聚焦第一个输入框
    setTimeout(() => {
        if (codeInputs.value[0]) {
            codeInputs.value[0].focus()
        }
    }, 0)
}
</script>

<style scoped>
.download-container {
    max-width: 800px;
    margin: 0 auto;
    padding: 0 2rem;
    min-height: 100vh;
    /* 使用视口高度 */
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    /* 改为居中对齐 */
}

.header {
    text-align: center;
    margin-bottom: 3rem;
}

.header h1 {
    color: var(--el-color-primary);
    font-size: 2.5rem;
    font-weight: 600;
    margin-bottom: 0.5rem;
    letter-spacing: 1px;
}

.subtitle {
    color: #606266;
    font-size: 1.1rem;
    opacity: 0.8;
}

.access-code-form {
    background: linear-gradient(145deg, #ffffff, #f0f2f5);
    padding: 3rem;
    border-radius: 16px;
    text-align: center;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.05);
    width: 100%;
    max-width: 500px;
    position: relative;
    backdrop-filter: blur(5px);
}

.access-code-form h2 {
    margin-bottom: 2rem;
    color: var(--el-color-primary);
    font-weight: 600;
    font-size: 1.5rem;
}

.code-input-wrapper {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 1.5rem;
}

.code-inputs {
    display: flex;
    gap: 12px;
    justify-content: center;
}

.code-digit {
    width: 60px;
    height: 70px;
    font-size: 1.8rem;
    font-weight: bold;
    text-align: center;
    border-radius: 12px;
    border: 2px solid #dcdfe6;
    background-color: white;
    transition: all 0.2s ease;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.04);
    color: var(--el-color-primary);
}

.code-digit:focus {
    border-color: var(--el-color-primary);
    box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
    outline: none;
}

.verify-btn {
    width: 100%;
    height: 50px;
    font-size: 1.1rem;
    border-radius: 12px;
    margin-top: 1rem;
    font-weight: 500;
    letter-spacing: 1px;
    transition: all 0.3s ease;
}

.verify-btn:hover:not(:disabled) {
    transform: translateY(-2px);
    box-shadow: 0 8px 15px rgba(0, 0, 0, 0.1);
}

.error-message {
    color: var(--el-color-danger);
    margin-top: 1.5rem;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    background-color: rgba(245, 108, 108, 0.1);
    padding: 10px 16px;
    border-radius: 8px;
    font-size: 0.95rem;
}

.file-info-card {
    background: linear-gradient(145deg, #ffffff, #f0f2f5);
    padding: 3rem;
    border-radius: 16px;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.05);
    width: 100%;
    max-width: 500px;
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;
}

.file-icon {
    color: var(--el-color-primary);
    margin-bottom: 1.5rem;
    background-color: rgba(64, 158, 255, 0.1);
    border-radius: 50%;
    width: 90px;
    height: 90px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.file-info-card h2 {
    color: #303133;
    margin-bottom: 2rem;
    font-weight: 600;
    font-size: 1.5rem;
}

.info-grid {
    display: grid;
    width: 100%;
    margin-bottom: 2rem;
    row-gap: 1.2rem;
}

.info-item {
    border-radius: 12px;
    padding: 1rem;
    background-color: rgba(245, 247, 250, 0.6);
    border: 1px solid #ebeef5;
}

.info-label {
    font-weight: 500;
    color: #606266;
    margin-bottom: 0.5rem;
    font-size: 0.9rem;
    text-transform: uppercase;
    letter-spacing: 1px;
}

.info-value {
    font-weight: 600;
    color: #303133;
    word-break: break-word;
}

.actions {
    display: flex;
    gap: 12px;
    margin-top: 1rem;
    width: 100%;
}

.download-btn,
.back-btn {
    flex: 1;
    height: 48px;
    border-radius: 12px;
    font-weight: 500;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    transition: all 0.3s ease;
}

.download-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 15px rgba(0, 0, 0, 0.1);
}

/* 修复整体高度问题，确保布局在各种设备上都居中显示 */
html,
body {
    height: 100%;
    margin: 0;
    padding: 0;
    overflow-x: hidden;
    display: flex;
    flex-direction: column;
    justify-content: center;
}

@media (max-width: 600px) {
    .download-container {
        padding: 2rem 1rem;
        justify-content: flex-start;
        /* 在小屏幕上调整为从顶部开始 */
        padding-top: 4rem;
        /* 增加顶部间距 */
    }

    .access-code-form,
    .file-info-card {
        padding: 2rem 1.2rem;
    }

    .code-digit {
        width: 50px;
        height: 60px;
        font-size: 1.5rem;
    }

    .actions {
        flex-direction: column;
    }

    .header h1 {
        font-size: 2rem;
    }
}
</style>